package com.qianheng.kit.web.support;

import com.qianheng.kit.web.util.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
@Order(Ordered.LOWEST_PRECEDENCE)//必须比TraceOncePerRequestFilter优先级低
public class BizRecordOncePerRequestFilter extends OncePerRequestFilter {

    @Value("${qh.OncePerRequestFilter1.demo:}")
    private String demo;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
        long start = System.currentTimeMillis();

        String uri = request.getRequestURI();
        if (uri.equals(demo)) {
            chain.doFilter(request, response);
            return;
        }

        try {
            chain.doFilter(request, response);
        } finally {
            try {
                bizRecord(start);
            } catch (Exception e) {
                log.error("业务日志记录失败", e);
            }

        }

    }

    private void bizRecord(long startTime) {
        ContentCachingRequestWrapper httpRequestWrapper = WebUtil.getHttpRequestWrapper();
        if (httpRequestWrapper == null) {
            log.info("没有httpRequestWrapper，不记录");
            return;
        }
        log.info("bizRecord 入参 {}", WebUtil.getHttpRequestJsonBody());
        log.info("bizRecord 出参 {}", WebUtil.getHttpResponseJsonBody());
        log.info("bizRecord {}", System.currentTimeMillis() - startTime);

    }
}
